$(function() {
	mui.init();
	//相册预览
	mui.previewImage();
	mui.ready(function() {
		//加载框
		mui.showLoading("正在加载..", ".warn-list");
	});
	// 图片追尾的数字
	var num = 0;
	//ajax请求处理数据

	//请求JSON	
	var userid = localStorage.getItem('userid');
	var token = localStorage.getItem('token');
	var caseid = localStorage.getItem('caseid');
	var url = domain + "/dtwbgl/jjprocessdesc.h5";
	var postData = {
		userid: userid,
		token: token,
		caseid: caseid,
	}


	// 获取图片
	getStoragePhoto();
	//添加相片
	mui('.upload_img').on('tap', 'a', function() {})
	mui('#btncameara').on('tap', 'a', function() {
		mui('#picture').popover('toggle'); // 先关闭弹出层
		// 调用相机
		// console.log(1);
		startCamera('startcamera');
		return false
	});
	// 调用相机
	function startCamera(param) {
		//创建event的对象实例。  
		// console.log(4);
		var event = document.createEvent('MouseEvents');
		// 3个参数：事件类型，是否冒泡，是否阻止浏览器的默认行为  
		event.initEvent("click", false, false);
		/*属性，随便自己定义*/
		//触发自定义事件oneating  
		var f = document.getElementById(param)
		f.dispatchEvent(event);
		$('#startcamera').off('change').on('change', function() {
			readURL(this);
			// console.log(5);
		});
	}

	// 把照片读取成base64格式
	function readURL(input) {
		mui.showLoading("正在加载..", ".mui-content");
		var uploadUrl = 'http://' + localStorage.getItem('middleserver') + ':' + localStorage.getItem(
			'uploadport') + '/';
		var downloadUrl = 'http://' + localStorage.getItem('middleserver') + ':' + localStorage.getItem(
			'downloadport') + '/';
		// 		if (checkPic() > 3) {
		// 			mui.toast("只能选择4张照片");
		// 			return;
		// 		};
		if (input.files && input.files[0]) {
			const
				reader = new FileReader();
			reader.readAsDataURL(input.files[0]);
			/*reader.onload = (e) => {
				$('#imgShow').attr('src', e.target.result);
			};*/
			reader.onload = function(e) {
				var base64info = e.target.result;
				// base64 										
				var blob = dataURItoBlob(base64info);
				var fd = new FormData();
				// var num = Math.round(new Date() / 1000) + Math.floor((Math.random() * 100) + 1);

				var img = 'sig_' + localStorage.getItem('caseid').trim() + '_' + num + '.jpg';
				fd.append("f", blob, img);
				$.ajax({
					url: uploadUrl + 'upload',
					type: 'POST',
					data: fd,
					// dataType: 'JSON',
					cache: false,
					processData: false,
					contentType: false,
					traditional: true,
					success: function(res) {
						//隐藏加载框
						mui.hideLoading(function() { //隐藏后的回调函数  
						});
						if (res == 'ok') {
							let src = downloadUrl + img;
							let li = '<li><span><img src="' + src + '" data-preview-src="' + src +
								'" data-preview-group="2" data-fn="' + img + '" height="70px" ></span></li>';
							$('#photo').append(li);
							$("input[name=files]").val('');
							mui.toast('上传成功');
							// local存储
							setStoragePhoto();
							num++;
							if (num >= 4) {
								mui.toast('最多传4张照片');
								$('.upload_img').remove();
							}

						} else {
							mui.toast('上传失败');
						}
					}
				});
			}
		}
	}

	// 图片存储
	function setStoragePhoto() {
		var piclist = [];
		$("#photo li").each(function(i, e) {
			var src = $(e).find('img').attr('src');
			var fn = $(e).find('img').data('fn');
			var item = {
				src: src,
				fn: fn
			}
			piclist.push(item);
		});
		localStorage.setItem('photo_' + localStorage.getItem('caseid'), JSON.stringify(piclist));
	}

	function getStoragePhoto() {
		var piclist = localStorage.getItem('photo_' + localStorage.getItem('caseid'));
		piclist = JSON.parse(piclist);

		var lis = '';
		if (!piclist) {
			return;
		}
		piclist.forEach(function(e, i) {
			console.log(e);
			lis += '<li><span><img src="' + e.src + '" data-preview-src="' + e.src +
				'" data-preview-group="2" data-fn="' + e.fn + '" height="70px" ></span></li>';
			num = (i + 1);
		});
		$('#photo').append(lis);
		if ($('#photo li').length >= 4) {
			$('.upload_img').remove();
		}
	}
	// 请求数据
	$.ajax(url, {
		// data: JSON.stringify(postData),
		data: postData,
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 30000, //超时时间
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		async: true, //true异步加载
		success: function(data) {
			if (data.code == 2001) {
				//返回值处理
				var postList = data.data;
				// 工单对应的ip
				var ctr_user = postList.ctr_user;
				var ctr_wbr = postList.ctr_wbr;
				var kind = postList.kind;
				localStorage.setItem('ctr_user', ctr_user);
				localStorage.setItem('ctr_wbr', ctr_wbr);
				localStorage.setItem('kind', kind);

				console.log(postList);
				$(".men").html(postList.gztypecn); //属性	
				$(".txtbox h2:nth-child(2) span").html(postList.caseid);
				$(".txtbox h2:nth-child(3) span").html(postList.xdtime);
				$(".txtbox h2:nth-child(4) span").html(postList.jdtime);
				$(".repair-type-box.monbox p:nth-child(1) span").html(postList.dttype);
				$(".repair-type-box.monbox p:nth-child(2) span").html(postList.dtdz);
				$(".repair-type-box.monbox p:nth-child(3) span").html(postList.dtcode);
				// 上报图片
				$(".upload").click(function() {
					$("input[name=files]").click();
				});
				// 总提交
				$('.submitAll').click(function() {
					submitAll(postList);
				});
				// 更换零件
				mui('.txtbox').on('tap', '.chang', function() {
					mui.openWindow({
						url: 'urgent-list-detail-parts.html',
						id: 'urgent-list-detail-parts.html'
					})
				})
				var ph = postList.wypiclist;
				var imlen = ph.length;
				var imhtml = '';
				var ip = localStorage.getItem('ip');
				var port = localStorage.getItem('port');
				console.log(port);
				var wyurl = 'http://' + configureIp + '/upimg/';
				console.log(wyurl);

				if (imlen != 0) {
					//添加图片
					ph.forEach(function(e, k) {
						var imgUrl = wyurl + e.url
						console.log(imgUrl);
						imhtml +=
							`<li><span><img src="${imgUrl}" data-preview-src="${imgUrl}"data-preview-group="1"></span>
						</li>`;
					})
					$('.monbox_img ul').append(imhtml);
				}


			} else if (data.code == 2002) {
				mui.alert(data.msg);
				mui.openWindow({
					url: '../../login.html',
					id: 'login.html'
				})
				console.log(data);
			} else {
				mui.alert(data.msg);
				mui.openWindow({
					url: '../../404.html',
					id: '404.html'
				})
			}
			mui.hideLoading(function() { //隐藏后的回调函数  
			});
		},
		error: function(xhr, type, errorThrown) { //异常处理； console.log(type);	
			mui.hideLoading(function() { //隐藏后的回调函数  
			});
			mui.alert(type);
			mui.openWindow({
				url: '../../login.html',
				id: 'login.html'
			})
		}
	});

	function submitAll(data) {
		// 发送请求
		// console.log(data);·
		// 处理结果
		mui.showLoading("正在加载..", ".warn-list");
		var texts = $(".chul textarea").val()
		console.log(texts);
		if (texts == "") {
			mui.hideLoading(function() { //隐藏后的回调函数  
			});
			mui.toast('请填写处理结果');
			return false;
		}
		// pic

		// pic
		var piclist = new Array();
		if ($("#photo li").length <= 0) {
			//隐藏加载框
			mui.hideLoading(function() { //隐藏后的回调函数  
			});
			mui.toast('请先上传图片');
			return false;
		}
		$("#photo li").each(function(i, e) {
			var src = $(e).find('img').attr('src');
			var item = {
				address: src,
				fn: src
			}
			piclist.push(item);
		});

		var now = getNowFormatDate();
		// pflist
		var jiej = $(".jiej input").val();
		var chul = $(".chul textarea").val();
		var pjlist = localStorage.getItem(data.caseid + '_pjlist');
		pjlist = JSON.parse(pjlist);
		// 经纬度
		//var lats = $('body').attr("data-lat");
		//var lags = $('body').attr("data-lng");

		// 2019-01-08
		var lats = localStorage.getItem('wbapplat');
		var lags = localStorage.getItem('wbapplng');

		//console.log("提交时坐标 " + lats+", " + lags);

		var postDatas = {
			userid: userid,
			token: token,
			kind: data.kind,
			caseid: caseid,
			actionid: data.actionid,
			long: lags,
			lat: lats,
			time: getNowFormatDate(),
			pz: chul,
			bz2: "",
			jjrs: jiej,
			piclist: piclist,
			pj: pjlist
		}
		console.log(postDatas);
		// return false;
		var Inurl = domain + "/dtwbgl/wbjjtj.h5";
		console.log("紧急提交数据 " + JSON.stringify(postDatas));
		$.ajax(Inurl, {
			data: JSON.stringify(postDatas),
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型	
			headers: {
				'Content-Type': 'application/json'
			},
			async: true, //true异步加载
			success: function(data) {
				if (data.code == 3001) {
					mui.toast('提交成功');
					// 						// success
					// 					mui.openWindow({
					// 						url: 'urgent-list.html#processing',
					// 						id: 'urgent-list.html'
					// 					})
					// window.location.replace('urgent-list.html#processing');
					window.history.go(-1);
				} else {
					mui.toast('提交失败');
					//隐藏加载框
					mui.hideLoading(function() { //隐藏后的回调函数  
					});

				}
				console.log(data);
			},
		});
	}


})
